package cfdt.ldl.web.helper;

import cfdt.ldl.core.system.SystemConstants;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import cfdt.common.enums.CommonCodeEnum;
import cfdt.redis.helper.RedisHelper;
import cfdt.common.constants.DefaultConstants;
import cfdt.common.exception.CodeException;
import cfdt.ldl.web.util.WebTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <pre>
 * Modify Information:
 * Author       Date          Description
 * ============ ============= ============================
 * liyuejiang      2021年1月20日
 * </pre>
 */
@Component
public class TokenSessionHelper {

    private static final Logger logger = LoggerFactory.getLogger(TokenSessionHelper.class);

    @Autowired
    RedisHelper redisHelper;

    /**
     * 使用Token信息Redis的前缀
     */
    public static String TOKEN_PRE_REDIS = SystemConstants.PROJECT + StrPool.COLON +SystemConstants.USER_PREFIX;

    /**
     * 获取redis中的值
     *
     * @param request
     * @param secret
     * @return
     * @throws CodeException
     */
    public Map<String, Object> getRedisValMap(HttpServletRequest request, String secret) throws CodeException {
        String accessToken = request.getHeader(DefaultConstants.ACCESS_TOKEN);
        if (StrUtil.isEmpty(accessToken)) {
            logger.error( " accessToken是空: " + accessToken);
            throw new CodeException(CommonCodeEnum.CODE_0004);
        }
        // 从token中获取userId
        String userId = WebTokenUtil.getUserId(accessToken, secret);

        // 从redis中获取redisValMap
        Object tokenObject = redisHelper.get(TOKEN_PRE_REDIS + userId);
        Map<String, Object> redisValMap = (Map<String, Object>) tokenObject;
        if (CollUtil.isEmpty(redisValMap)) {
            logger.error(" redisValMap是空: " + redisValMap);
            throw new CodeException(CommonCodeEnum.CODE_0004);
        }
        return redisValMap;

    }

    /**
     * 刷新tokenSession
     *
     * @param userId
     */
    public void refreshTokenSession(String userId) {
        redisHelper.expire(TOKEN_PRE_REDIS + userId, SystemConstants.sessionTimeOut);
    }

    /**
     * 添加session
     *
     * @param userId
     * @param redisValMap
     */
    public void addTokenSession(String userId, Map<String, Object> redisValMap) {
        // Key
        String redisKey = TOKEN_PRE_REDIS + userId;

        // 如果存在则删除
        if(redisHelper.hasKey(redisKey)){
            redisHelper.del(redisKey);
        }

        // 加入Redis
        redisHelper.setValue(redisKey, redisValMap, SystemConstants.sessionTimeOut);
    }

}
